package controllers

import (
	"crypto/md5"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"news_website_db/cache"
	"news_website_db/models"
	"time"
)

type UserController struct {
	beego.Controller
}

func Md5(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	return fmt.Sprintf("%x", has)
}
func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "账号或密码为空",
		}
		c.ServeJSON()
		return
	}
	var user models.User
	user.Username = username
	user.Password = Md5(password)
	if user.Register() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "注册失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "注册成功",
	}
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "账号或密码为空",
		}
		c.ServeJSON()
		return
	}
	var user models.User
	user.Username = username
	user.Password = password
	key := "Login_err_count_" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "登录次数过多,请稍后再试",
		}
		c.ServeJSON()
		return
	}
	if user.Login(username) != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "登录失败",
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}
	if user.Password != Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码不正确",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
	}
	c.ServeJSON()
	return
}
